package org.dftproject.pgv.core.racp;

import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dftproject.gedcom.core.GedcomPerson;
import org.dftproject.gedcom.core.IGedcom;
import org.dftproject.gedcom.core.Line;
import org.dftproject.genesis.data.IAttribute;
import org.dftproject.genesis.data.genealogy.GenealogyConstants;
import org.dftproject.genesis.data.genealogy.IPerson;
import org.dftproject.genesis.data.impl.AttributeImpl;
import org.dftproject.pgv.core.PGVDataProvider;

public class PGVPerson extends GedcomPerson {
	
	private final static Pattern urlPattern = Pattern.compile("^(https?://.*?/)[^/]*$");
	
	private boolean sameAsInit = false;
	
	public PGVPerson(IGedcom gedcom, String xref, Line record) {
		super(gedcom, xref, record);
	}
	
	@Override
	public Set<IAttribute> getAttributes() {
		if (!sameAsInit)
			initSameAs();
		return super.getAttributes();
	}
	
	@Override
	public Set<IAttribute> getAttributes(String name) {
		if (!sameAsInit && GenealogyConstants.sameAs.equals(name))
			initSameAs();
		return super.getAttributes(name);
	}
	
	protected void initSameAs() {
		sameAsInit = true;
		
		for (Line line : getRecord().getChildren("RFN")) {
			String[] parts = line.getValue().split(":");
			if (parts.length == 2 && !"".equals(parts[0]) && !"".equals(parts[1])) {
				String serviceUrl = null;
				String dbid = null;
				
				Line resource = getGedcom().getRecord(parts[0]);
				for (Line resourceLine : resource.getChildren(new String[] { "URL", "_DBID" })) {
					if ("URL".equals(resourceLine.getTag()))
						serviceUrl = resourceLine.getValue();
					else if ("_DBID".equals(resourceLine.getTag()))
						dbid = resourceLine.getValue();
				}
				
				if (serviceUrl != null && dbid != null) {
					Matcher matcher = urlPattern.matcher(serviceUrl);
					if (matcher.matches()) {
						// Get the parts of the URL
						
						String url = matcher.group(1);
						
						Session session = PGVDataProvider.getSession(url);
						IGedcom gedcom = new PGVGedcom(session, dbid);
						IPerson person = gedcom.getPerson(parts[1]);
						if (person != null)
							addAttribute(new AttributeImpl(GenealogyConstants.sameAs, person));
					}
				}
			}
		}
	}

}
